package com.example.vv.model.home;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.aip.asrwakeup3.core.mini.AutoCheck;
import com.baidu.speech.EventListener;
import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.baidu.speech.asr.SpeechConstant;
import com.bumptech.glide.Glide;
import com.example.vv.R;
import com.example.vv.fragmentWork.entity.ArticleEntity;
import com.example.vv.fragmentWork.entity.BannerEntity;
import com.example.vv.fragmentWork.entity.TopEntity;
import com.example.vv.fragmentWork.mvp.MvpFragment;
import com.example.vv.fragmentWork.utlis.LogUtils;
import com.example.vv.fragmentWork.utlis.ShareUtils;
import com.example.vv.fragmentWork.utlis.UserInfo;
import com.example.vv.fragmentWork.view.CustomerTitleBar;
import com.example.vv.model.accountDetails.AIDActivity;
import com.example.vv.model.home.base.adapter.MyLoader;
import com.example.vv.model.home.base.adapter.TopRecycleViewAdapter;
import com.example.vv.model.home.base.contract.HomeContract;
import com.example.vv.model.home.base.presenter.HomePresenter;
import com.example.vv.model.homeDetail.HIDActivity;
import com.example.vv.model.integral.IntegralActivity;
import com.example.vv.model.search.SearchActivity;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class HomeFragment extends MvpFragment<HomeContract.View, HomePresenter> implements HomeContract.View, EventListener {


    @BindView(R.id.home_title)
    CustomerTitleBar homeTitle;
    @BindView(R.id.home_banner)
    Banner homeBanner;
    @BindView(R.id.home_recycler)
    RecyclerView homeRecycler;
    @BindView(R.id.home_smart)
    SmartRefreshLayout homeSmart;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.nsv)
    NestedScrollView nsv;
    @BindView(R.id.floatingActionButton)
    FloatingActionButton floatingActionButton;
    @BindView(R.id.et)
    TextView et;
    @BindView(R.id.btn_voice)
    ImageButton btnVoice;
    @BindView(R.id.btn_voice2)
    Button btnVoice2;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.home_navigation)
    NavigationView homeNavigation;
    @BindView(R.id.home_drawer)
    DrawerLayout homeDrawer;
    UserInfo userInfo;
    View view;
    TextView user;
    private BottomSheetBehavior mBottomSheetBehavior;
    private boolean logTime = true;
    private EventManager asr;
    protected boolean enableOffline = false; // 测试离线命令词，需要改成true
    private static final String API_KEY = "LjGboFpMZxx5SvV1lQw0bkyU";
    private static final String APP_ID = "20665826";
    private static final String SECRET_KEY = "rBywHLl5w16h7tgdTsR2KCzp0vFyOZ5b";
    AnimationDrawable background2;
    private List<TopEntity> listTop;
    List<String> image = new ArrayList<>();
    List<String> title = new ArrayList<>();


    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public int initLayout() {
        return R.layout.fragment_home;
    }

    @Override
    public HomePresenter initPresenter() {
        return new HomePresenter();
    }



    @RequiresApi(api = Build.VERSION_CODES.M)
    @SuppressLint("ResourceAsColor")
    @Override
    public void initView() {
        int peekHeight;
        mBottomSheetBehavior = BottomSheetBehavior.from(nsv);
        peekHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
        mBottomSheetBehavior.setPeekHeight(peekHeight);//设置最小高度
        mBottomSheetBehavior.setHideable(false);//设置是否可隐藏
        mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        homeTitle.getLeft_img().setVisibility(View.VISIBLE);
        homeTitle.getRight_rl().setVisibility(View.VISIBLE);
        homeTitle.getLeft_img().setImageResource(R.mipmap.ic_menu);
        background2 = (AnimationDrawable) btnVoice.getBackground();
        initListener();
        initPermission();
        initMenu();
    }

    @Override
    public void lazyLoad() {
        presenter.setBannerData();
        presenter.setTopData();
        if (refresh) {
            presenter.setArticleData(i + "");
        }
        presenter.getImageData();
    }

    /**
     * enableOffline设为true时，在onCreate中调用
     * 基于SDK离线命令词1.4 加载离线资源(离线时使用)
     */
    private void loadOfflineEngine() {
        Map<String, Object> s1 = new LinkedHashMap<String, Object>();
        s1.put(SpeechConstant.DECODER, 2);
        s1.put(SpeechConstant.ASR_OFFLINE_ENGINE_GRAMMER_FILE_PATH, "assets://baidu_speech_grammar.bsg");
        asr.send(SpeechConstant.ASR_KWS_LOAD_ENGINE, new JSONObject(s1).toString(), null, 0, 0);
    }

    /**
     * 语音权限请求
     */
    private void initPermission() {
        // 基于sdk集成1.1 初始化EventManager对象
        asr = EventManagerFactory.create(getMContext(), "asr");
        // 基于sdk集成1.3 注册输出事件类
        asr.registerListener(this); //  EventListener 中 onEvent方法

        if (enableOffline) {
            loadOfflineEngine(); // 测试离线命令词请开启, 测试 ASR_OFFLINE_ENGINE_GRAMMER_FILE_PATH 参数时开启
        }

        String[] permissions = {
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
        };
        ArrayList<String> applyLists = new ArrayList<>();
        for (String permission : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(getMContext(), permission)) {
                applyLists.add(permission);
                //进入这里代表没有权限
            }
        }
        String tmpList[] = new String[applyLists.size()];
        if (!applyLists.isEmpty()) {
            //请求权限
            ActivityCompat.requestPermissions(getActivity(), applyLists.toArray(tmpList), 123);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);//android6.0以上授权的动态回调
    }

    /**
     *
     */
    private void intiVoice() {

    }


    int i, j = 0;
    boolean refresh;
    @SuppressLint("WrongConstant")
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initListener() {
        homeSmart.autoRefresh();
        homeSmart.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                homeSmart.finishLoadMore(1000);
                /**
                 *刷新再度请求首页文章数据
                 */
                presenter.setArticleData(i + "");
                LogUtils.Log("refresh");
                i++;
//                if (i == 2) {
//                    i = 0;
//                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                presenter.setTopData();
                if (adapter!=null) {
                    title.clear();
                    image.clear();
                    presenter.setBannerData();
                    presenter.getImageData();
                    if (adapter.getItemCount() > listTop.size()) {
                        refresh = true;
                        presenter.setArticleData(0 + "");
                    }
                }
                homeSmart.finishRefresh(1000);
            }
        });

        scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            /**
             * @param view
             * @param i x
             * @param i1 y
             * @param i2 oldx
             * @param i3 oldy
             */
            @SuppressLint("ResourceAsColor")
            @Override
            public void onScrollChange(View view, int i, int i1, int i2, int i3) {
                if (i1 > i3) {
                    if (i1 > 400) {
                        homeTitle.getRight_img().setVisibility(View.GONE);
                    }
                }
                if (i1 < i3) {
                    if (i1 < 350) {
                        homeTitle.getRight_img().setVisibility(View.VISIBLE);
                    }
                }
            }
        });
        //悬浮按钮 显示或隐藏笔记界面
        floatingActionButton.setOnClickListener(view -> {
            if (j == 0) {
                nsv.startAnimation(AnimationUtils.loadAnimation(getMContext(), R.anim.note));
                nsv.setVisibility(View.VISIBLE);
                j++;

            } else {
                nsv.startAnimation(AnimationUtils.loadAnimation(getMContext(), R.anim.note_out));
                nsv.setVisibility(View.GONE);
                j = 0;
            }
        });

        /**
         * 长按录音
         */
        btnVoice2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        btnVoice.setVisibility(View.VISIBLE);
                        btnVoice.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.note2));
                        onStartVoice();
                        Toast.makeText(getMContext(), "开始录音", Toast.LENGTH_SHORT).show();
                        break;
                    case MotionEvent.ACTION_UP:
                        btnVoice.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.note_out));
                        btnVoice.setVisibility(View.INVISIBLE);
                        onStopVoice();
                        Toast.makeText(getMContext(), "结束录音", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
                return false;
            }
        });

        /**
         * 搜索实现
         */
        homeTitle.getRight_img().setOnClickListener(view -> {
            Intent intent = new Intent(getActivity(), SearchActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        });

    }

    /**
     * 基于SDK集成2.2 发送开始事件
     * 点击录音按钮开始录音
     * 测试参数填在这里
     */
    private void onStartVoice() {
        if (TextUtils.isEmpty(et.getText())) {
            et.setText("");
        }
        Map<String, Object> s1 = new LinkedHashMap<String, Object>();
        String event = null;
        event = SpeechConstant.ASR_START; // 开始录音

        if (enableOffline) {
            s1.put(SpeechConstant.DECODER, 2); //离在线的并行策略
        }
        // 基于SDK集成2.1 设置识别参数
        s1.put(SpeechConstant.ACCEPT_AUDIO_VOLUME, false);
        (new AutoCheck(getMContext(), new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 100) {
                    AutoCheck autoCheck = (AutoCheck) msg.obj;
                    synchronized (autoCheck) {
                        String message = autoCheck.obtainErrorMessage(); // autoCheck.obtainAllMessage();
                        Log.w("AutoCheckMessage", message); //log中查看代码
                    }

                }
            }
        }, enableOffline)).checkAsr(s1);
        String json = null;
        json = new JSONObject(s1).toString();
        asr.send(event, json, null, 0, 0);
        background2.start();

    }

    /**
     * 停止录音
     */
    public void onStopVoice() {
        asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0);
        background2.stop();
    }

    /**
     * 获取语音识别结果
     *
     * @param s
     * @param s1
     * @param bytes
     * @param i
     * @param i1
     */
    @Override
    public void onEvent(String s, String s1, byte[] bytes, int i, int i1) {
        String result = "", res = "";

        if (s.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {
            // 识别相关的结果都在这里

            if (s1.contains("\"final_result\"")) {
                try {
                    JSONObject jsonObject = new JSONObject(s1);
                    result = jsonObject.getString("best_result");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        printLog(result);
    }

    /**
     * 输出语音识别结果
     *
     * @param text
     */
    private void printLog(String text) {
        Log.i(getClass().getName(), text + "");
        if (TextUtils.isEmpty(et.getText())) {
            et.setText(text);
        } else {
            et.append(text);
        }
    }


    @Override
    public void initData() {
        view = homeNavigation.getHeaderView(0);
        user = view.findViewById(R.id.menu_user);

        if (ShareUtils.isLogin) {
            userInfo = ShareUtils.getUserInfo(getActivity());
            user.setText(userInfo.getName());
        }else {
            user.setText("未登录");
        }
    }

    @Override
    public void doBusiness() {
    }

    @Override
    public View titleBar() {
        return homeTitle;
    }


    @Override
    public Context getMContext() {
        return getActivity();
    }


    @Override
    public void getBannerData(List<BannerEntity> bannerEntities) {
        image = presenter.setImageData(bannerEntities);
        title = presenter.setTitleData(bannerEntities);
        homeBanner.setIndicatorGravity(BannerConfig.CENTER)
                .setDelayTime(3000)
                .setImages(image)
                .setBannerTitles(title)
                .setImageLoader(new MyLoader())
                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE)
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int position) {
                        EventBus.getDefault().postSticky(bannerEntities.get(position));
                        Intent intent = new Intent(getActivity(), AIDActivity.class);
                        startActivity(intent);
                    }
                })
                .start();
    }

    @Override
    public void onStart() {
        super.onStart();
        initData();
    }

    /**
     * 获取置顶数据
     */
    TopRecycleViewAdapter adapter;

    @Override
    public void getTopData(List<TopEntity> topEntities) {
        listTop = topEntities;
        adapter = new TopRecycleViewAdapter(getMContext(), topEntities, R.layout.item_home_list);
        homeRecycler.setAdapter(adapter);
        RecycleClick();
    }

    /**
     * 获取首页文章数据
     *
     * @param articleEntities
     */
    List<ArticleEntity.DatasBean> datas;
    List<ArticleEntity.DatasBean> datasAll = new ArrayList<>();
    @Override
    public void getArticleData(ArticleEntity articleEntities) {
        datas = articleEntities.getDatas();
        for (int k = datas.size() - 10; k >= 0; k--) {
            datas.remove(k);
        }
        if (datas.size() == 0) {

        } else {
            datasAll.addAll(0,datas);
            adapter.setList(datas);
            RecycleClick();
            Log.i("TAG", "getArticleData: datasAll.size--"+datasAll.size());
            if (refresh) { }else {
            }
        }

    }

    private void RecycleClick() {
        adapter.setOnItemClickListener((adapter, v, position) -> {
            Log.i("TAG", "OnItemClickListener: "+position);
            Bundle bundle = new Bundle();
            if (position<=listTop.size()-1) {
                getMContext().startActivity(new Intent(getActivity(), HIDActivity.class)
                        .putExtra("data1",listTop.get(position)));
            }else {
            getMContext().startActivity(new Intent(getActivity(), HIDActivity.class)
                    .putExtra("data2",datasAll.get(position-listTop.size())));
            }
        });
    }

    @Override
    public void getImageData(String url) {
        if (url!=null) {
            getActivity().runOnUiThread(()->{
                ImageView imageView = view.findViewById(R.id.meu_bg);
                Glide.with(this)
                        .load(url)
                        .into(imageView);
                EventBus.getDefault().postSticky(url);
            });
        }
    }

    private void initMenu() {
        homeTitle.getLeft_img().setOnClickListener(v->{
            homeDrawer.openDrawer(homeNavigation);
        });
        homeNavigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()){
                    case R.id.home_guangchang:
                        startActivity(new Intent(getActivity(), IntegralActivity.class));
                        homeDrawer.closeDrawer(homeNavigation);
                        break;
                    case R.id.home_love:
                        homeDrawer.closeDrawer(homeNavigation);
                        break;
                    case R.id.home_setting:
                        homeDrawer.closeDrawer(homeNavigation);
                        break;
                    case R.id.home_jifen:
                        homeDrawer.closeDrawer(homeNavigation);
                        break;
                    case R.id.home_todu:
                        homeDrawer.closeDrawer(homeNavigation);
                        break;

                }
                return true;
            }
        });
    }

    /**
     * 释放资源
     */
    @Override
    public void onDestroy() {
        asr.unregisterListener(this);
        super.onDestroy();
    }

}